#!/bin/bash

# 解析命令行参数
harbor_addr=$1
harbor_repo=$2
project=$3
version=$4
container_port=$5
host_port=$6

# 构建镜像名称
imageName="$harbor_addr/$harbor_repo/$project:$version"

echo "Image Name: $imageName"

# 获取现有容器ID
containerId=$(docker ps -a | grep "$project" | awk '{print $1}')

echo "Container ID: $containerId"

# 如果存在同名容器，则停止并移除它
if [ ! -z "$containerId" ]; then
  echo "Stopping and removing existing container..."
  docker stop "$containerId"
  docker rm "$containerId"
fi

# 检查本地是否已存在相同版本的镜像
tag=$(docker images | grep "$project" | awk '{print $2}')

echo "Existing Tags: $tag"

if [[ "$tag" == "$version" ]]; then
  echo "Removing existing image..."
  docker rmi -f "$imageName"
fi

# 登录到Harbor仓库（建议使用更安全的方式传递密码）
echo "Logging into Harbor..."
echo "WARNING! Using --password via the CLI is insecure. Use --password-stdin."
docker login -u admin -p Harbor12345 "$harbor_addr"

# 拉取最新的镜像
echo "Pulling latest image..."
docker pull "$imageName"

# 运行新的容器
echo "Running new container..."
docker run -d -p "$host_port":"$container_port" --name "$project" "$imageName"

echo "SUCCESS!"
